package com.kc.framework.web.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.kc.common.utils.DateUtils;
import com.kc.framework.web.exception.user.OssException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 云存储
 */
@Service
public class CloudStorageService {
    private OSSClient client;
    private String endPoint = "oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI4FdQrimwvRKyq5z59BKe";
    private String accessKeySecret = "FeQb6KRBaZojRM59r0SfeBMjt05VuW";
    private String bucketName = "kachuo";
    private String domain = "https://oss.kachuo.com";

    public CloudStorageService() {
        // 初始化
        init();
    }

    private void init() {
        client = new OSSClient(endPoint, accessKeyId,
                accessKeySecret);
    }

    /**
     * 文件路径
     *
     * @param prefix 前缀
     * @param suffix 后缀
     * @return 返回上传路径
     */
    public String getPath(String prefix, String suffix) {
        // 生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 文件路径
        String path = DateUtils.dateTime() + "/" + uuid;
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path + suffix;
    }


    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(bucketName, path, inputStream);
        } catch (Exception e) {
            throw new OssException("上传文件失败，请检查配置信息");
        }
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, path);
        generatePresignedUrlRequest.setExpiration(expiration);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        String signUrl = client.generatePresignedUrl(generatePresignedUrlRequest).toString();
        System.out.println(signUrl);
        return domain + "/" + path;
    }

    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath("", suffix));
    }

    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath("/", suffix));
    }
}
